/**
 * 上传图片
 * @param {Object} options - 可选配置项
 * @param {Number} options.count - 选择图片数量，默认1
 * @param {Array} options.sourceType - 选择类型 ['album', 'camera']，默认相册
 * @param {Array} options.sizeType - 图片类型 ['original', 'compressed']
 * @returns {Promise}
 */
export function uploadImage(options = {}) {
	return new Promise((resolve, reject) => {
		// 默认配置
		const config = {
			count: options.count || 1,
			sourceType: options.sourceType || ['album'],
			sizeType: options.sizeType || ['original', 'compressed']
		};

		uni.chooseImage({
			...config,
			success: (res) => {
				const tempFilePath = res.tempFilePaths[0];

				uni.uploadFile({
					url: 'https://pcdn.hbkfu.com/api/common/upload',
					filePath: tempFilePath,
					name: 'file',
					formData: {
						user: 'test',
						...options.formData // 支持自定义 formData
					},
					header: {
						token: uni.getStorageSync('token'),
						...options.header // 支持自定义 header
					},
					success: (res) => {
						if (res.statusCode === 200) {
							try {
								const data = JSON.parse(res.data);
								resolve(data.data.fullurl); // 返回完整URL
							} catch (e) {
								reject('返回数据格式错误');
							}
						} else {
							uni.$u.toast("上传失败");
							reject('服务器返回错误');
						}
					},
					fail: (err) => {
						uni.$u.toast("网络异常");
						reject(err);
					}
				});
			},
			fail: (err) => {
				uni.$u.toast("选择图片失败");
				uni.hideLoading();
				reject(err);
			}
		});
	});
}

/**
 * 微信小程序支付
 * @param {Object} payData - 支付参数对象
 * @returns {Promise}
 */
export function wxMiniProgramPay(payData) {
	return new Promise((resolve, reject) => {
		if (!payData) {
			uni.$u.toast("支付参数错误");
			return reject(new Error('支付参数不完整'));
		}

		const params = {
			timeStamp: payData.timeStamp,
			nonceStr: payData.nonceStr,
			package: payData.package,
			signType: payData.signType || 'HMAC-SHA256',
			paySign: payData.paySign,
			success(res) {
				uni.$u.toast("支付成功");
				uni.navigateTo({
					url: '/pages/mine/allOrders/allOrders'
				});
				resolve({
					success: true,
					res
				});
			},
			fail(err) {
				if (err.errMsg === 'requestPayment:fail cancel') {
					uni.$u.toast("取消支付");
					reject({
						success: false,
						code: 'cancel',
						err
					});
				} else {
					uni.$u.toast("支付失败");
					reject({
						success: false,
						code: 'fail',
						err
					});
				}
			}
		};

		uni.requestPayment(params);
	});
}

// 时间戳转换
function formatTimestamp(timestamp, fmt = 'YYYY-MM-DD HH:mm:ss') {
	const date = new Date(timestamp * 1000)

	const padZero = (n) => n.toString().padStart(2, '0')

	const year = date.getFullYear()
	const month = padZero(date.getMonth() + 1)
	const day = padZero(date.getDate())
	const hour = padZero(date.getHours())
	const minute = padZero(date.getMinutes())
	const second = padZero(date.getSeconds())

	return fmt
		.replace('YYYY', year)
		.replace('MM', month)
		.replace('DD', day)
		.replace('HH', hour)
		.replace('mm', minute)
		.replace('ss', second)
}

export default formatTimestamp;